package com.gensdai.leliang.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gensdai.leliang.R;
import com.gensdai.leliang.adapter.AutoAdapter;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.common.bean.SearchBean;
import com.gensdai.leliang.db.SearchDao;
import com.gensdai.leliang.entity.parseBean.BaseParse;
import com.gensdai.leliang.entity.parseBean.BaseParseList;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.view.flowtag.FlowTagLayout;
import com.gensdai.leliang.view.flowtag.OnInitSelectedPosition;
import com.gensdai.leliang.view.flowtag.OnTagClickListener;
import com.gensdai.leliang.view.flowtag.OnTagSelectListener;
import com.jakewharton.rxbinding2.widget.RxTextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * 搜索界面
 * Created by zsxx on 2017/7/25.
 */


public class SearchActivity extends BaseActivity {


    @BindView(R.id.delete)
    ImageView delete;
    private Disposable subscription;

    @BindView(R.id.search)
    AppCompatAutoCompleteTextView search;
    @BindView(R.id.search_flow_layout)
    FlowTagLayout searchFlowLayout;


    private List<String> mVals = null;
    AutoAdapter autoAdapter;
    TagAdapters mSizeTagAdapter;
    @Override
    protected String getTitleStr() {
        return null;
    }

    @Override
    protected boolean isShowBackButton() {
        return false;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_search;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

//        mVals = new ArrayList<>();
//        mVals.add("油");
//        mVals.add("护肤品");
//        mVals.add("连衣裙");
//        mVals.add("贝亲婴儿");
//        mVals.add("三层隔热");
//        mVals.add("蓝");
//        mVals.add("贝亲婴儿镊子");
//        mVals.add("贝亲");
//        mVals.add("镊子ccc");
//        mVals.add("贝亲婴儿专用清洁镊子");
//        mVals.add("贝亲");
//        mVals.add("贝亲婴儿");
//        mVals.add("贝亲婴儿专用清洁镊子");
//        mVals.add("油");
//        mVals.add("连衣裙");
//        mVals.add("贝亲婴儿");
//        mVals.add("三层隔热");



        search.setDropDownVerticalOffset(8);
        search.setThreshold(1);
    }


    private void toSearchResult(String str){
        Intent it = new Intent(SearchActivity.this,ActivitySearchResult.class);
        it.putExtra(ActivitySearchResult.EXTRA_SEARCH_STR,str);
        startActivity(new Intent(it));
    }


    @OnClick(R.id.back)
    public void onBackClick(View v) {
        onBackPressed();
    }
    @OnClick(R.id.delete)
    public void onDeleteHistory(View v){
        if(searchFlowLayout != null){
            new SearchDao(SearchActivity.this).deletAll();
            searchFlowLayout.removeAllViews();
        }
    }

    private void initViewAction() {
        search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String searchstr = search.getText().toString().trim();
                        if(!TextUtils.isEmpty(searchstr)){
                            new SearchDao(SearchActivity.this).addSearchStr(searchstr);
                            toSearchResult(searchstr);
                        }
                    return true;
                }
                return false;
            }
        });



        subscription = RxTextView.textChanges(search)
                .subscribeOn(AndroidSchedulers.mainThread())
                .debounce(1000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) //延迟处理
                .observeOn(Schedulers.io())//对下游的Observable起作用
                .filter(new Predicate<CharSequence>() {
                    @Override
                    public boolean test(@NonNull CharSequence charSequence) throws Exception {
                        return charSequence.toString().trim().length() > 0;
                    }
                })
//                .observeOn(AndroidSchedulers.mainThread())//对下游的Observable起作用  因为在switchmap中有网络请求 所以不能在mainThread线程中执行
                .switchMap(new Function<CharSequence, ObservableSource<BaseParseList<SearchBean>>>() {
                    @Override
                    public ObservableSource<BaseParseList<SearchBean>> apply(@NonNull CharSequence charSequence) throws Exception {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("productName", charSequence.toString());
                        return RetrofitFactory.getInstance().API().getSearchHintList(params)
                                ;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseParseList<SearchBean>>() {
                    @Override
                    public void accept(@NonNull BaseParseList<SearchBean> stringBaseParseList) throws Exception {

                        autoAdapter = new AutoAdapter(SearchActivity.this,stringBaseParseList.data);

//        ArrayAdapter<string> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,list);
                        search.setAdapter(autoAdapter);
                        autoAdapter.notifyDataSetChanged();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {

                    }
                });
    }


    public static class TagAdapters<T> extends BaseAdapter implements OnInitSelectedPosition {

        private final Context mContext;
        private final List<T> mDataList;

        public TagAdapters(Context context) {
            this.mContext = context;
            mDataList = new ArrayList<>();
        }

        @Override
        public int getCount() {
            return mDataList.size();
        }

        @Override
        public Object getItem(int position) {
            return mDataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = LayoutInflater.from(mContext).inflate(R.layout.tag_item, null);

            TextView textView = (TextView) view.findViewById(R.id.tv_tag);
            T t = mDataList.get(position);

            if (t instanceof String) {
                textView.setText((String) t);
            }
            return view;
        }

        public void onlyAddAll(List<T> datas) {
            mDataList.addAll(datas);
            notifyDataSetChanged();
        }

        public void clearAndAddAll(List<T> datas) {
            mDataList.clear();
            onlyAddAll(datas);
        }

        @Override
        public boolean isSelectedPosition(int position) {
            if (position % 2 == 0) {
                return true;
            }
            return false;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!subscription.isDisposed()) {
            subscription.dispose();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initViewAction();

        showSoftInputFromWindow(this,search);
        mVals = new SearchDao(SearchActivity.this).findList();
        mSizeTagAdapter = new TagAdapters<>(this);
        searchFlowLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_NONE);
        searchFlowLayout.setAdapter(mSizeTagAdapter);
        searchFlowLayout.setOnTagClickListener(new OnTagClickListener() {
            @Override
            public void onItemClick(FlowTagLayout parent, View view, int position) {
                String b = (String)parent.getAdapter().getItem(position);
                toSearchResult(b);
            }
        });
        mSizeTagAdapter.clearAndAddAll(mVals);
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}
